// Pinia Store
import { defineStore } from "pinia";
import { login, getUserInfo } from '/@/api/user';
import to from 'await-to-js';
import { useStorage } from '@vueuse/core'
interface State {
  userId: number | null;
  name: string;
  token: string;
  authRole: string[]
}

export const useUserStore = defineStore("user", {
  // convert to a function
  state: (): State => ({

    userId: null,
    name: undefined,
    token: sessionStorage.getItem('token') || '',
    authRole: []
  }),
  getters: {
    loggedIn: state => state.userId !== null
    // must define return type because of using `this`
  },
  actions: {
    // no context as first argument, use `this` instead
    SET_NAME(val) {
      this.name = val;
    },
    SET_TOKEN(val) {
      this.token = val
      useStorage('token', val, sessionStorage)
    },
    SET_AUTH_ROLE(role: string[]) {
      this.authRole = role
    },
    async getUserInfo(): Promise<any> {
      const [err,res]=await to(getUserInfo())
      if(!err){
        this.SET_AUTH_ROLE(res.data)
        return Promise.resolve(res.data)
      }else{
        return Promise.reject()
      }
    },
    async login(form: { username: string; password: string | number }) {
      const [err, res] = await to(login(form))
      if (!err) {
        this.SET_TOKEN(res.data.accessToken)
        return res
      }
    }
  }
});
